from django.http import HttpResponse
from rest_framework import status
from rest_framework.response import Response
from users.models import User
from .serializers import ImageCodeCheckSerializer
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from django_redis import get_redis_connection
from meiduo_again.libs.captcha.captcha import captcha
from verifications import constants
import random
# Create your views here.


class UsernameCountView(APIView):
    """判断用户名是否存在"""
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        data = {
            'username': username,
            'count': count
        }
        return Response(data)


class MobileCountView(APIView):
    """判断手机号是否存在"""
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            'mobile': mobile,
            'count': count
        }
        return Response(data)



class ImageCodeView(APIView):
    """图形验证码"""  # /image_codes/(?P<image_code_id>[\w-]+)/
    def get(self, request, image_code_id):
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.setex("image_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        return HttpResponse(image, content_type="images/jpg")


class SMSCodeView(GenericAPIView):
    """短信验证码"""
    serializer_class = ImageCodeCheckSerializer

    def get(self, request, mobile):
        # 获取查询字符串的参数
        # 关于校验工作，我们交给序列化器来完成
        serializer = self.get_serializer(data=request.query_params)
        # 异常被触发，会给前端抛出４００的错误
        serializer.is_valid(raise_exception=True)
        sms_code = '%06d' % random.randint(0, 999999)
        redis_conn = get_redis_connection('verify_codes')
        # 设置管道,一起发送
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES//60, sms_code)
        pl.setex('flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 'anything')
        pl.execute()
        return Response(data={'message': '发送成功'}, status=status.HTTP_200_OK)









